package match

import (
	"bbtradeByGo/pkg/email"
	"bbtradeByGo/pkg/gmysql"
	"bbtradeByGo/pkg/gredis"
	"bbtradeByGo/pkg/logging"
	"strings"

	help "bbtradeByGo/model/match/model"
	"database/sql"
	"errors"
	"fmt"
)


//OrderList 查询订单列表
func OrderList(mc *help.MCondition) ([]*help.MCondition, error){
	orderList := make([]*help.MCondition, 0)
	var (
		where      []string
		args       []interface{}
		query      string
	)

	fields := "*"

	// 组合query
	query = fmt.Sprintf(`SELECT %s from abc_orders a where 1=1 `, fields)
	if mc.Id != 0 {
		where = append(where, `and a.id = ?`)
		args = append(args, mc.Id)
	}
	if mc.IdGt != 0{
		where = append(where, `and a.id > ?`)
		args = append(args, mc.IdGt)
	}
	if mc.OrderStatus != 0{
		where = append(where, `and a.order_status = ?`)
		args = append(args, mc.OrderStatus)
	}
	if mc.OrderIn != 0 && mc.OrderIn == 1{
		where = append(where, `and (a.order_status = 0 or a.order_status = 1)`)
	}

	//if mc.Status == 0{
	//	where = append(where, `and (a.order_status = 0 or a.order_status = 1)`)
	//}

	if len(where) > 0 {
		query = query +strings.Join(where, " ")
	}

	query = query + " ORDER BY id asc "

	if (mc.PageNo != 0 && mc.PageSize != 0){
		query = query + " LIMIT ?, ?"
		args = append(args, (mc.PageNo-1)*mc.PageSize, mc.PageSize)
	}

	if (mc.GroupBy != nil){
		query = query + " GROUP BY ? "
		args = append(args, mc.GroupBy)
	}

	query = gmysql.DB.Rebind(query)

	if err := gmysql.DB.Unsafe().Select(&orderList, query, args...); err != nil {
		if err != sql.ErrNoRows {
			email.SendMail("model.match.OrderList", err.Error())
			logging.Error("model.match.OrderList err:", err)
			return nil, err
		}
	}
	return orderList, nil
}


//OrderUpDate 更新订单
func OrderUpDate(mc *help.MCondition, fields *help.Field ) (error){
	var (
		where      []string
		value      []string
		args       []interface{}
		query      string
	)

	// 组合query
	query = fmt.Sprintf(`update abc_orders set `)

	if fields.OrderStatus != 0 {
		value = append(value, `order_status = ? `)
		args  = append(args, fields.OrderStatus)
	}

	if fields.Tradenum != 0 {
		value = append(value, `tradenum = ? `)
		args  = append(args, fields.Tradenum)
	}

	if fields.Poundage != 0 {
		value = append(value, `poundage = ? `)
		args  = append(args, fields.Poundage)
	}

	value = append(value, `trademoney = ? `)
	args  = append(args, fields.Trademoney)

	value = append(value, `surplus = ? `)
	args  = append(args,fields.Surplus)

	if mc.Id != 0 {
		where = append(where, `where id = ? `)
		args  = append(args, mc.Id)
	}else{
		return  errors.New("model.match.OrderUpDate err")
	}
	if len(value) > 0 {
		query = query +strings.Join(value, ",")
	}
	if len(where) > 0 {
		query = query +strings.Join(where, " ")
	}

	_, err := gmysql.DB.Exec(query, args...)
	if err != nil {
		email.SendMail("model.match.OrderUpDate", err.Error())
        logging.Error("model.match.OrderUpDate err:", err)
	}
	return  nil
}


// GenerateTrade生成一条交易数据
func GenerateTrade(fields *help.Field) {
	 _, err := gmysql.DB.Exec(`INSERT INTO abc_trade (uid, order_id, base_currency_id, currency_id, price,
              number, poundage, create_time, type, tradetype, taker) VALUES (?,?,?,?,?,?,?,?,?,?,?)`, fields.UId,
		 fields.OrderId, fields.BaseCurrencyId, fields.CurrencyId, fields.Price, fields.Number, fields.Poundage,
		 fields.CreateTime, fields.Type, fields.Tradetype, fields.Taker)

	 if err != nil {
		 email.SendMail("model.match.GenerateTrade", err.Error())
		 logging.Error("model.match.GenerateTrade err:", err)
	 }
}


//FeeGet 获取手续费
func FeeGet(cid, bcid int)  (*help.Fee, error){
	res := make([]*help.Fee, 0)
	if err := gmysql.DB.Unsafe().Select(&res, ` SELECT buy_pdg, sell_pdg FROM abc_currency_pair WHERE 
     cid = ? AND bcid = ? `, cid, bcid); err != nil{
		email.SendMail("model.match.FeeGet", err.Error())
		logging.Error("model.match.FeeGet err: ", err)
	}
     if len(res) > 0 {
     	return  &help.Fee{
				 SellFee: res[0].SellPdg,
				 BuyFee:  res[0].BuyPdg,
			 }, nil

		 }else{

		 	key := fmt.Sprintf("交易对%d_%d不存在",cid, bcid)
		 	return nil, errors.New(key)
     }

	return nil, nil
}

//OrderCancel 取消订单
func OrderCancel(condition *help.MCondition) {
	switch condition.Tradetype {
	    case 1:
			_, err := gmysql.DB.Exec(`update abc_orders set order_status = 3 where id= ?`, condition.Id)
			if err != nil {
				email.SendMail("model.match.OrderCancel err1", err.Error())
				logging.Error("model.match.OrderCancel err1:", err)
			}
			if condition.Type == 0 {
				_, err = gmysql.DB.Exec(`update abc_currency_user set number_frz = number_frz - ? where uid = ? AND currency_id = ?`,
					condition.Surplus, condition.Uid, condition.CurrencyId)
				if err != nil {
					email.SendMail("model.match.OrderCancel err2", err.Error())
					logging.Error("model.match.OrderCancel err2:", err)
				}
			}
			lKey := fmt.Sprintf("currency:match:cancel:%d/%d", condition.BaseCurrencyId, condition.CurrencyId)
			gredis.LPush(lKey, condition.Id)
	}
}


//AssetsList  资产列表
func AssetsList(condition *help.Condition) ([]*help.Assets, error){
	asset := make([]*help.Assets, 0)
	field := "*"
	var (
		where      []string
		args       []interface{}
		query      string
	)

	// 组合query
	query = fmt.Sprintf(`SELECT %v from abc_currency_user a where 1=1 `, field)

	if condition.Id != 0 {
		where = append(where, ` and a.id = ?`)
		args  = append(args, condition.Id)
	}

	if condition.UId != 0 {
		where = append(where, `and a.uid = ?`)
		args  = append(args, condition.UId)
	}

	if condition.CurrencyId != 0 {
		where = append(where, `and a.currency_id = ?`)
		args  = append(args, condition.CurrencyId)
	}

	if len(where) > 0 {
		query = query +strings.Join(where, " ")
	}
	query = gmysql.DB.Rebind(query)

	if err := gmysql.DB.Unsafe().Select(&asset, query, args...); err != nil {
		if err != sql.ErrNoRows {
			return nil, err
		}
	}
	return asset, nil

}

//AssetsUpdate 资产更新
func AssetsUpdate(condition *help.Condition, assets *help.Assets)  error{
	var (
		value      []string
		where      []string
		args       []interface{}
		query      string
	)

	// 组合query
	query = fmt.Sprintf(`update abc_currency_user set `)

	if assets.Number != 0 {
		value = append(value, ` number = ? `)
		args  = append(args, assets.Number)
	}

	if assets.NumberFrz != 0 {
		value = append(value, ` number_frz = ? `)
		args  = append(args, assets.NumberFrz)
	}

	if condition.Id != 0 {
		where = append(where, ` where id = ?`)
		args  = append(args, condition.Id)
	}

	if len(value) > 0 {
		query = query +strings.Join(value, ",")
	}
	if len(where) > 0 {
		query = query +strings.Join(where, " ")
	}

	_, err := gmysql.DB.Exec(query, args...)
	if err != nil {
		email.SendMail("model.match.AssetsUpdate ", err.Error())
		logging.Error("model.match.AssetsUpdate err:", err)
	}
	return  nil
}

//AssetsAdd 增加资产
func AssetsAdd(assets *help.Assets) {

	_, err := gmysql.DB.Exec(`INSERT INTO abc_currency_user (uid, currency_id, number) VALUES (?,?,?)`,
		assets.UId, assets.CurrencyId, assets.Number)
	if err != nil {
		email.SendMail("model.match.AssetsAdd ", err.Error())
		logging.Error("model.match.AssetsAdd err:", err)
	}
}














